<template>
  <view class="container">
    <image class="img" mode="aspectFill" src="/static/images/service-background.png"></image>

    <view class="info-box">
      <view class="name">{{ info.name }}</view>
      <view class="price">超值价：
        <text>{{ info.price }}元/次</text>
      </view>
    </view>

    <view class="tab">
      <view :class="index == 0 ? 'active' : ''" @click="changeTab(0)">基本信息</view>
      <view :class="index == 1 ? 'active' : ''" @click="changeTab(1)">价格说明</view>
      <view :class="index == 2 ? 'active' : ''" @click="changeTab(2)">预订须知</view>
    </view>

    <scroll-view enable-flex scroll-y class="article" :style="'height: ' + article_height + 'vh;'">
      <rich-text :nodes="content"></rich-text>
    </scroll-view>

    <view class="footer">
      <button class="btn" open-type="contact" plain>联系客服</button>
      <view class="btn pay-btn" @click="payNow">立即购买</view>
    </view>

    <view id="mask" v-if="show_login" @click.stop>
      <view class="mask-content" @click.stop>
        <form @submit="formSubmit" class="main-content">
          <view class="title">完善资料</view>
          <button open-type="chooseAvatar" @chooseavatar="getAvatar" class="avatar-btn">
            <image class="btnImg" :src="avatar_path" mode="aspectFill"></image>
          </button>
          <input type="text" :value="avatar" name="avatar" style="display: none">

          <view class="row">
            <view class="left">昵称</view>
            <input type="nickname" @focus="this.showLoginModel = true" @input="this.showLoginModel = true" :value="username" name="nickname" class="input" placeholder="请输入昵称">
          </view>

          <view class="row" style="border-top: none">
            <view class="left">手机号</view>
            <button open-type="getPhoneNumber" :plain="true" @getphonenumber="getPhoneNumber" class="mobile-btn" v-if="!mobile">获取手机号</button>
            <block v-else>
              <input type="number" :value="mobile" name="mobile" style="display: none">
              <view class="input">{{mobile}}</view>
            </block>
          </view>

          <view class="agree-box">
            <button hover-class="none" :type="'mini'" :plain="true" class="item agree-btn" open-type="agreePrivacyAuthorization">
              <checkbox :checked="is_agree" @click="doAgree" class="checkbox round color" color="#32A4FF" style="background: #FFF;border: none"/>
            </button>

            <view class="box">
              阅读并接受
              <text class="text" @click="openPrivacy">{{ privacyContractName }}</text>
            </view>
          </view>

          <input type="text" :value="openid" name="openid" style="display: none">

          <view class="btn-box">
            <button :plain="true" class="button cancel" @click="this.show_login = false">取消</button>
            <button form-type="submit" class="button save">保存</button>
          </view>
        </form>
      </view>
    </view>
  </view>
</template>

<script>
import http from '@/utils/http'

export default {
  data() {
    return {
      hospital_id: 0,
      info: [],
      content: '',
      index: 0,
      article_height: 44,
      show_login: false,
      privacyContractName: '《陪诊预约隐私保护指引》',
      is_agree: false,
      avatar: 0,
      avatar_path: '../../static/images/default_avatar.png',
      mobile: '',
      username: '',
      showLoginModel: false,
      openid: ""
    };
  },

  methods: {
    changeTab: function (index) {
      switch (index) {
        case 1:
          this.content = this.info.price_des;
          break;
        case 2:
          this.content = this.info.reserve_des;
          break;
        default:
          this.content = this.info.basic_des;
          break;
      }
      this.index = index
    },

    payNow: function (){
      var user_id = uni.getStorageSync('user_id');

      if(user_id){
        this.pay();
      }else{
        uni.showLoading({
          title: '自动登录中...',
          mask: true
        })

        uni.login({
          success: result => {
            var code = result.code;

            this.$http.post('/index/Api/openidToUserid', {code}).then(res => {
              uni.hideLoading();
              if (res.data.result === 1) {
                var user_id = res.data.data;
                uni.setStorageSync('user_id', user_id)

                this.pay();
              } else {
                this.show_login = true;
              }
            })
          }
        })
      }
    },

    openPrivacy: function () {
      uni.openPrivacyContract()
    },

    getAvatar: function (e) {
      var {avatarUrl} = e.detail;

      uni.uploadFile({
        url: http.config.baseURL + '/Upload/UploadFile/uniUploadPicture', //服务端图片上传接口地址
        filePath: avatarUrl,
        name: 'download',
        formData: {},
        success: res => {
          res = JSON.parse(res.data)
          if (res.result === 1) {
            uni.showToast({
              title: '上传头像成功'
            })
            this.showLoginModel = true;
            this.avatar_path = res.data.path;
            this.avatar = res.data.id;
          } else {
            uni.showToast({
              title: res.msg,
              icon: 'none'
            })
          }
        },
        fail: err => {
          setTimeout(() => {
            uni.hideLoading();
            uni.showToast({
              title: '图片上传失败',
              icon: 'none'
            })
          }, 500)
        }
      })
    },

    getPhoneNumber: function (e){
      var code = e.detail.code;
      this.$http.post('/index/Api/getMobile', {code}).then(res => {
        if (res.data.result === 1) {
          this.mobile = res.data.data
        }else{
          this.$common.doErrorResult(res)
        }
      })
    },

    doAgree: function () {
      this.is_agree = !this.is_agree;
    },

    formSubmit: function (e) {
      var formData = e.detail.value,
        timestamp = Date.parse(new Date()),//该值除以1000就是当前的时间戳,
        sync_timestamp = uni.getStorageSync('timestamp') ? uni.getStorageSync('timestamp') : 0,//获取时间戳缓存,
        now_timestamp = timestamp / 1000,
        long_time = now_timestamp - sync_timestamp;//距离上次点击按钮经过的时长（秒）,

      if (!this.is_agree) {
        uni.showToast({
          title: '请阅读并勾选小程序隐私保护指引',
          icon: 'none'
        })
        return;
      }

      uni.showLoading({
        title: '保存中...',
        mask: true
      })

      if (long_time > 3) {
        //将当前时间戳存为缓存
        uni.setStorageSync('timestamp', timestamp / 1000);

        uni.login({
          success: result => {
            var code = result.code;

            this.$http.post('/index/Api/getOpenid', {code}).then(res => {
              if (res.data.result === 1) {
                formData.openid = res.data.data;

                this.$http.post('/Index/Api/login', formData).then(res => {
                  uni.removeStorageSync('timestamp');
                  uni.hideLoading();

                  if (res.data.result === 1) {
                    var user_id = res.data.data;
                    uni.setStorageSync('user_id', user_id)

                    this.show_login = false;

                    this.pay();
                  } else {
                    this.$common.doErrorResult(res);
                  }
                })
              } else {
                this.$common.doErrorResult(res);
              }
            })
          }
        })
      }
    },

    pay: function () {
      var user_id = uni.getStorageSync('user_id'),
        service_id = this.info.id,
        hospital_id = this.hospital_id,
        timestamp = Date.parse(new Date()),//该值除以1000就是当前的时间戳,
        sync_timestamp = uni.getStorageSync('timestamp') ? uni.getStorageSync('timestamp') : 0,//获取时间戳缓存,
        now_timestamp = timestamp / 1000,
        long_time = now_timestamp - sync_timestamp;//距离上次点击按钮经过的时长（秒）

      if (long_time > 3) {
        //将当前时间戳存为缓存
        uni.setStorageSync('timestamp', timestamp / 1000);

        uni.showLoading({
          title: '支付中...',
          mask: true
        })

        this.$http.post('/index/Api/pay', {user_id, service_id, hospital_id}).then(res => {
          uni.removeStorageSync('timestamp');
          if (res.data.result == 1) {
            var {order_sn, pay_data} = res.data.data;
            /********主要代码********/
            if (pay_data) {
              uni.getProvider({
                service: 'payment',
                success: result => {
                  var provider = result.provider;
                  if (provider) {
                    uni.requestPayment({
                      provider: provider,
                      orderInfo: {order_sn},
                      timeStamp: pay_data.timeStamp,
                      nonceStr: pay_data.nonceStr,
                      package: pay_data.package,
                      signType: pay_data.signType,
                      paySign: pay_data.paySign,
                      success: res => {
                        uni.hideLoading();
                        uni.reLaunch({
                          url: '/pages/order_list/order_list'
                        })
                      },
                      fail: function (res) {
                        uni.showToast({
                          title: '取消支付',
                          icon: 'none'
                        })
                      }
                    })
                  } else {
                    uni.showToast({
                      title: '取消支付',
                      icon: 'none'
                    })
                  }
                }
              });
            }
            /********主要代码********/
          } else {
            uni.hideLoading();
            this.$common.doErrorResult(res);
          }
        })
      }
    },
  },

  onLoad: function (options) {
    var id = options.id;

    this.hospital_id = options.hospital_id ? options.hospital_id : 0;

    // 同步获取系统信息
    var {windowHeight, windowWidth} = uni.getSystemInfoSync();
    if (windowHeight / windowWidth < 1.9) this.article_height = 34;

    this.$http.post('/index/Api/serviceDetail', {id}).then(res => {
      if (res.data.result == 1) {
        this.info = res.data.data
        this.content = this.info.basic_des
      } else {
        uni.showToast({
          icon: 'none',
          title: res.data.msg,
          success: () => {
            setTimeout(() => {
              uni.navigateBack()
            }, 1000)
          }
        })
      }
    })
  },
}
</script>

<style lang="scss">
.container {
  padding: 0 20rpx 40rpx 20rpx;

  .img {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 320rpx;
    z-index: -1;
  }

  .info-box {
    width: calc(100% - 40rpx);
    background: #fff;
    border-radius: 20rpx;
    margin-top: 280rpx;
    padding: 40rpx 20rpx;
    display: flex;
    flex-direction: column;

    .name {
      font-size: 32rpx;
      font-weight: bold;
      margin-bottom: 40rpx;
    }

    .price {
      text {
        color: #F18958;
      }
    }
  }

  .tab {
    display: flex;
    justify-content: space-around;
    margin-top: 40rpx;
    font-size: 28rpx;
  }

  .active {
    color: $main-color;
  }

  .article {
    height: 34vh;
    margin-top: 20rpx;
    background: #fff;
    border-radius: 20rpx;
    padding: 20rpx;
    width: calc(100% - 40rpx);
  }

  .footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 120rpx;
    background: #fff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx;

    .btn {
      padding: 0 100rpx;
      font-size: 32rpx;
      color: $main-color;
      border-radius: 40rpx;
      border: 2rpx solid $main-color;
    }

    .pay-btn {
      color: #fff;
      background: linear-gradient(to right, #FFFFFF, #0984CA);
      border: none;
      padding: 20rpx 100rpx;
    }
  }
}
</style>

